package com.longtop.sp.mapdao.meta;

import java.sql.SQLException;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import org.springframework.jdbc.core.JdbcTemplate;

import com.longtop.sp.mapdao.util.ComparatorIgnoreCase;


public class TableMetaDataPool {
	private static final Map tmRSMetaDataPool = Collections
			.synchronizedMap(new TreeMap(new ComparatorIgnoreCase()));

	private static boolean DEV_MODE = true;

	private TableMetaDataPool() {
	}

	public static boolean canCacheSchema(String tableName) {
		return !DEV_MODE;
	}

	// 仅仅依靠表名作为主键，是有可能发生错误的，尤其是在有多个数据源，进行数据交换时。
	public static synchronized TableMetaData getMetaData(JdbcTemplate jt,
			String tableName) throws SQLException {
		if (!canCacheSchema(tableName))
			return new TableMetaData(jt, tableName);

		Object key = tableName;
		TableMetaData meta = (TableMetaData) tmRSMetaDataPool.get(key);
		if (meta == null) {
			meta = new TableMetaData(jt, tableName);
			tmRSMetaDataPool.put(key, meta);
		}

		return meta;
	}
}